'use strict';

const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('处理订单纠纷云函数被调用，参数:', event)
  
  // 管理员访问检查
  const isAdminAccess = event.isAdmin || true // 暂时允许所有访问
  let uid = null
  
  if (!isAdminAccess) {
    const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
    if (!token) {
      return { code: 401, msg: '未登录' }
    }
    
    const uniId = uniIdCommon.createInstance({ context })
    const tokenRes = await uniId.checkToken(token)
    if (tokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    uid = tokenRes.uid
  } else {
    console.log('管理员访问，跳过token验证')
    uid = 'admin'
  }

  const { taskId, action, reason, adminId = 'admin', sendNotification = false, taskInfo = {}, systemSender = {} } = event
  
  if (!taskId || !action) {
    return { code: 400, msg: '参数不完整' }
  }

  const db = uniCloud.database()
  const timestamp = Date.now()
  
  try {
    console.log(`开始处理纠纷 - 任务ID: ${taskId}, 操作: ${action}`)
    
    // 获取任务信息
    const taskResult = await db.collection('taskList').doc(taskId).get()
    if (!taskResult.data || taskResult.data.length === 0) {
      return { code: 404, msg: '任务不存在' }
    }
    
    const task = taskResult.data[0]
    console.log('找到任务:', task.title)
    
    // 记录纠纷处理日志
    const disputeLog = {
      task_id: taskId,
      task_title: task.title,
      action: action,
      reason: reason,
      admin_id: adminId,
      original_status: task.status,
      timestamp: timestamp,
      create_time: new Date()
    }
    
    // 根据操作类型处理任务
    let updateData = {}
    let resultMessage = ''
    
    switch (action) {
      case 'cancel_and_refund':
        updateData = {
          status: 'cancelled',
          cancel_time: timestamp,
          cancel_reason: reason,
          dispute_status: 'cancelled_by_admin',
          update_time: timestamp
        }
        resultMessage = '任务已取消并安排退款'
        
        // TODO: 触发退款流程
        await handleRefund(task, reason, adminId)
        break
        
      case 'cancel_task':
        updateData = {
          status: 'cancelled',
          cancel_time: timestamp,
          cancel_reason: reason,
          dispute_status: 'cancelled_by_admin',
          update_time: timestamp
        }
        resultMessage = '任务已取消'
        break
        
      case 'force_complete':
        updateData = {
          status: 'completed',
          complete_time: timestamp,
          complete_reason: reason,
          dispute_status: 'force_completed',
          update_time: timestamp
        }
        resultMessage = '任务已强制完成'
        
        // TODO: 触发支付流程给执行者
        await handlePayment(task, reason, adminId)
        break
        
      case 'force_payment':
        // 发送支付提醒，不改变任务状态
        updateData = {
          payment_reminder_time: timestamp,
          payment_reminder_reason: reason,
          update_time: timestamp
        }
        resultMessage = '已发送支付催促通知'
        
        // TODO: 发送支付提醒通知
        await sendPaymentReminder(task, reason, adminId)
        break
        
      case 'extend_time':
        // 延长任务时间7天
        const extendDays = 7
        const newDeadline = (task.deadline || timestamp) + (extendDays * 24 * 60 * 60 * 1000)
        updateData = {
          deadline: newDeadline,
          extend_time: timestamp,
          extend_reason: reason,
          dispute_status: 'time_extended',
          update_time: timestamp
        }
        resultMessage = `任务时间已延长${extendDays}天`
        break
        
      case 'extend_payment_time':
        // 延长支付时间24小时
        const extendHours = 24
        const newPaymentDeadline = (task.payment_deadline || timestamp) + (extendHours * 60 * 60 * 1000)
        updateData = {
          payment_deadline: newPaymentDeadline,
          payment_extend_time: timestamp,
          payment_extend_reason: reason,
          update_time: timestamp
        }
        resultMessage = `支付时间已延长${extendHours}小时`
        break
        
      case 'change_executor':
        updateData = {
          status: 'pending', // 回到待接单状态
          executor_changed_time: timestamp,
          executor_changed_reason: reason,
          dispute_status: 'executor_changed',
          update_time: timestamp
        }
        resultMessage = '任务执行者变更流程已启动'
        
        // TODO: 清除当前参与者记录
        await clearTaskParticipants(taskId, reason, adminId)
        break
        
      case 'admin_mediate':
        updateData = {
          dispute_status: 'admin_mediating',
          mediate_start_time: timestamp,
          mediate_reason: reason,
          update_time: timestamp
        }
        resultMessage = '已介入协调处理'
        break
        
      case 'suspend_task':
        updateData = {
          dispute_status: 'suspended',
          suspend_time: timestamp,
          suspend_reason: reason,
          update_time: timestamp
        }
        resultMessage = '任务已暂停处理'
        break
        
      default:
        return { code: 400, msg: '不支持的操作类型' }
    }
    
    // 更新任务状态
    console.log('更新任务状态:', updateData)
    await db.collection('taskList').doc(taskId).update(updateData)
    
    // 保存纠纷处理日志
    disputeLog.new_status = updateData.status || task.status
    disputeLog.result_message = resultMessage
    
    try {
      await db.collection('dispute_logs').add(disputeLog)
      console.log('纠纷处理日志已保存')
    } catch (logError) {
      console.log('保存纠纷日志失败:', logError)
      // 不影响主流程
    }
    
    console.log('纠纷处理完成:', resultMessage)
    
    // 发送系统通知（如果启用）
    let notificationStatus = null
    if (sendNotification) {
      notificationStatus = await sendDisputeSystemNotifications(task, action, resultMessage, reason, adminId)
    }
    
    return {
      code: 200,
      msg: '纠纷处理成功',
      data: {
        taskId: taskId,
        action: action,
        result: resultMessage,
        timestamp: timestamp,
        notificationStatus: notificationStatus
      }
    }
    
  } catch (error) {
    console.error('处理纠纷失败:', error)
    return {
      code: 500,
      msg: '纠纷处理失败: ' + error.message,
      error: error.toString()
    }
  }
}

// 处理退款逻辑
async function handleRefund(task, reason, adminId) {
  console.log(`处理退款 - 任务: ${task.title}, 金额: ${task.reward}`)
  
  const db = uniCloud.database()
  
  try {
    // 创建退款记录
    const refundRecord = {
      task_id: task._id,
      user_id: task.publisher_id || task.user_id,
      amount: task.reward,
      reason: reason,
      status: 'processing',
      admin_id: adminId,
      create_time: new Date(),
      type: 'dispute_refund'
    }
    
    await db.collection('refund_records').add(refundRecord)
    console.log('退款记录已创建')
    
    // TODO: 集成真实的支付系统退款API
    
  } catch (error) {
    console.log('处理退款失败:', error)
  }
}

// 处理支付逻辑
async function handlePayment(task, reason, adminId) {
  console.log(`处理支付 - 任务: ${task.title}, 金额: ${task.reward}`)
  
  const db = uniCloud.database()
  
  try {
    // 创建支付记录
    const paymentRecord = {
      task_id: task._id,
      executor_id: task.executor_id, // 需要从参与者中获取
      amount: task.reward,
      reason: reason,
      status: 'processing',
      admin_id: adminId,
      create_time: new Date(),
      type: 'dispute_payment'
    }
    
    await db.collection('payment_records').add(paymentRecord)
    console.log('支付记录已创建')
    
    // TODO: 集成真实的支付系统API
    
  } catch (error) {
    console.log('处理支付失败:', error)
  }
}

// 发送支付提醒
async function sendPaymentReminder(task, reason, adminId) {
  console.log(`发送支付提醒 - 任务: ${task.title}`)
  
  // TODO: 发送消息通知给发布者
  // 可以通过uni-push、短信、邮件等方式
  
  console.log('支付提醒已发送')
}

// 清除任务参与者
async function clearTaskParticipants(taskId, reason, adminId) {
  console.log(`清除任务参与者 - 任务ID: ${taskId}`)
  
  const db = uniCloud.database()
  
  try {
    // 删除或标记参与者记录
    await db.collection('activity_participants')
      .where({
        activity_id: taskId,
        activity_type: 'task'
      })
      .update({
        status: 'removed_by_admin',
        remove_time: Date.now(),
        remove_reason: reason,
        admin_id: adminId
      })
    
    console.log('任务参与者已清除')
    
  } catch (error) {
    console.log('清除参与者失败:', error)
  }
}

// 发送纠纷处理系统通知
async function sendDisputeSystemNotifications(task, action, resultMessage, reason, adminId) {
  console.log(`发送纠纷处理系统通知 - 任务: ${task.title}, 操作: ${action}`)
  
  const notificationStatus = {
    publisherSent: false,
    participantSent: false,
    failed: []
  }
  
  try {
    const db = uniCloud.database()
    
    // 发送给发布者的通知
    if (task.publisher_id || task.user_id) {
      const publisherId = task.publisher_id || task.user_id
      
      const publisherNotification = {
        user_id: publisherId,
        type: 'task_status',
        category: 'task',
        title: '任务纠纷处理结果',
        content: `您发布的任务"${task.title}"的纠纷已由管理员处理。处理结果：${resultMessage}`,
        related_id: task._id,
        related_type: 'task',
        priority: 'high',
        action_url: `/pages/task/detail?id=${task._id}`,
        action_text: '查看任务详情',
        create_time: new Date()
      }
      
      try {
        await db.collection('notification-messages').add(publisherNotification)
        notificationStatus.publisherSent = true
        console.log(`系统通知已发送给发布者: ${publisherId}`)
      } catch (error) {
        console.error('发送发布者通知失败:', error)
        notificationStatus.failed.push('发布者')
      }
    }
    
    // 发送给执行者的通知（如果有）
    if (task.receiver_id) {
      // 使用新schema的receiver_id
      const participantNotification = {
        user_id: task.receiver_id,
        type: 'task_status',
        category: 'task',
        title: '任务纠纷处理结果',
        content: `您接受的任务"${task.title}"的纠纷已由管理员处理。处理结果：${resultMessage}`,
        related_id: task._id,
        related_type: 'task',
        priority: 'high',
        action_url: `/pages/task/detail?id=${task._id}`,
        action_text: '查看任务详情',
        create_time: new Date()
      }
      
      try {
        await db.collection('notification-messages').add(participantNotification)
        notificationStatus.participantSent = true
        console.log(`系统通知已发送给接收者: ${task.receiver_id}`)
      } catch (error) {
        console.error('发送接收者通知失败:', error)
        notificationStatus.failed.push('接收者')
      }
    } else if (task.participants && task.participants.length > 0) {
      // 兼容旧的participants格式
      for (const participant of task.participants) {
        const participantId = participant.user_id
        if (participantId) {
          const participantNotification = {
            user_id: participantId,
            type: 'task_status',
            category: 'task',
            title: '任务纠纷处理结果',
            content: `您参与的任务"${task.title}"的纠纷已由管理员处理。处理结果：${resultMessage}`,
            related_id: task._id,
            related_type: 'task',
            priority: 'high',
            action_url: `/pages/task/detail?id=${task._id}`,
            action_text: '查看任务详情',
            create_time: new Date()
          }
          
          try {
            await db.collection('notification-messages').add(participantNotification)
            notificationStatus.participantSent = true
            console.log(`系统通知已发送给参与者: ${participantId}`)
          } catch (error) {
            console.error('发送参与者通知失败:', error)
            notificationStatus.failed.push('参与者')
          }
        }
      }
    }
    
    console.log('纠纷系统通知发送完成:', notificationStatus)
    return notificationStatus
    
  } catch (error) {
    console.error('发送纠纷系统通知失败:', error)
    notificationStatus.failed.push('系统错误')
    return notificationStatus
  }
}


